import { ElMessage } from 'element-plus'

export const useFileHook = () => {
  // 上传Excel文件
  const uploadExcelFile = () => {
    return new Promise((resolve) => {
      const input = document.createElement('input')
      input.type = 'file'
      input.accept = '.xls,.xlsx,.xlsm'
      input.click()
      function getFile(e) {
        const file = e.target.files[0]
        const type = file.name.split('.')
        const fileType = type[type.length - 1]
        if (input.accept.includes(fileType)) {
          resolve(file)
        } else {
          ElMessage.error('Excel文件上传格式错误')
        }
        input.removeEventListener('change', getFile)
      }

      input.addEventListener('change', getFile)
    })
  }

  // 上传图片文件
  const uploadImageFile = () => {
    return new Promise((resolve) => {
      const input = document.createElement('input')
      input.type = 'file'
      input.accept = '.jpg,.png,.jpeg,.gif'
      input.click()

      function getFile(e) {
        const file = e.target.files[0]
        const type = file.name.split('.')
        const fileType = type[type.length - 1]
        if (input.accept.includes(fileType)) {
          resolve(file)
        } else {
          ElMessage.error('图片上传格式错误')
        }
        input.removeEventListener('change', getFile)
      }

      input.addEventListener('change', getFile)
    })
  }

  // 上传模型文件
  const uploadModelFile = () => {
    return new Promise((resolve) => {
      const input = document.createElement('input')
      input.type = 'file'
      input.accept = '.gltf,.glb'
      input.click()

      function getFile(e) {
        const file = e.target.files[0]
        const type = file.name.split('.')
        const fileType = type[type.length - 1]
        // if (fileSize > VIDEO_MAX_SIZE) {
        //   errorMsg(上传的模型文件不能超过${VIDEO_MAX_SIZE}M)
        // } else
        if (input.accept.includes(fileType)) {
          resolve(file)
        } else {
          ElMessage.error('模型上传格式错误')
        }
        input.removeEventListener('change', getFile)
      }

      input.addEventListener('change', getFile)
    })
  }

  // 下载文件
  const downloadFile = (data, name) => {
    const link = document.createElement('a')
    link.download = name
    link.style.display = 'none'
    const blob = new Blob([data], {
      type: 'application/vnd.ms-excel;charset=utf-8'
    })
    link.href = URL.createObjectURL(blob)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }

  return {
    uploadExcelFile,
    uploadImageFile,
    uploadModelFile,
    downloadFile
  }
}
